/**
 * www.easyplatform.cn ©2016
 */
package cn.easyplatform.studio.cmd.entity;

import cn.easyplatform.entities.BaseEntity;
import cn.easyplatform.entities.EntityInfo;
import cn.easyplatform.studio.dao.EntityDao;
import cn.easyplatform.studio.interceptor.Command;
import cn.easyplatform.studio.interceptor.CommandContext;

/**
 * @author <a href="mailto:shiny_vc@163.com">陈云亮</a> <br/>
 * @since 2.0.0 <br/>
 */
public class CopyCmd implements Command<BaseEntity> {

	private String newId;

	private String oldId;

	public CopyCmd(String oldId, String newId) {
		this.oldId = oldId;
		this.newId = newId;
	}

	@Override
	public BaseEntity execute(CommandContext cc) {
		EntityDao dao = cc.getEntityDao();
		EntityInfo e = dao
				.getEntry(cc.getProject().getEntityTableName(), oldId);
		if (e != null) {
			try {
				cc.beginTx();
				e.setId(newId);
				e.setStatus('C');
				e.setUpdateUser(cc.getUser().getUserId());
				dao.save(cc.getProject().getId(), cc.getProject()
						.getEntityTableName(), e);
				cc.commitTx();
				cc.getEntityLockProvider().lock(cc.getProject().getId(), newId);
				e.setStatus('U');
				BaseEntity entity = dao.getEntity(cc.getProject().getEntityTableName(), newId);
				return entity;
				//return TransformerFactory.newInstance().transformFromXml(e);
			} catch (Exception ex) {
				cc.rollbackTx();
				throw (RuntimeException) ex;
			} finally {
				cc.closeTx();
			}
		}
		return null;
	}

}
